package com.dymedia.aibo.app.utils;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;

import com.dymedia.aibo.app.MainApp;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import timber.log.Timber;

public class Utils {
    public static void findFocusView(Activity activity){
        Window window = activity.getWindow();
        if (window != null){
            View rootView = window.getDecorView();
            if (rootView != null){
                View view = rootView.findFocus();
                if (view != null){
                    Timber.e("focusView: "+rootView.getClass().getName());
                }
            }
        }
    }
    public static String getProductInfo(Context context){
        try {
            JSONObject obj = new JSONObject();
            obj.put("AppVersion", context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName);
            obj.put("OsVersion", Build.VERSION.RELEASE);
            obj.put("ProductManufacturer", Build.MANUFACTURER);
            obj.put("ProductModel", Build.MODEL);
            obj.put("Product", Build.PRODUCT);
            obj.put("ProductSerial", Build.SERIAL);
            return obj.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

    public static String getMACAddress(String interfaceName) {
        try {
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces) {
                Log.e("Utils", "intf.getName(): "+intf.getName());
                if (interfaceName != null) {
                    if (!intf.getName().equalsIgnoreCase(interfaceName)) continue;
                }
                byte[] mac = intf.getHardwareAddress();
                if (mac==null) return "";
                StringBuilder buf = new StringBuilder();
                for (int idx=0; idx<mac.length; idx++)
                    buf.append(String.format("%02X:", mac[idx]));
                if (buf.length()>0) buf.deleteCharAt(buf.length()-1);

                Log.e("Utils", "intf.mac: "+buf.toString());
                return buf.toString();
            }
        } catch (Exception ex) { } // for now eat exceptions
        return "";
    }

    public static String getTerminalMac(){
        String[] args = { "operator", "-m", "Sd7Dk9TpyS", "-c", "busybox ifconfig" };
        Map<String, String> output = executeCmdWithOutput(args);
        String isok = output.get("isok");
        String firstline = output.get("firstline");
        if (isok != null && firstline !=null){
            int start = firstline.indexOf("HWaddr ");
            if (start > 0){
                int end = firstline.indexOf("\n");
                if (end < 0){
                    end = firstline.length();
                }
                if (end > 0)
                    return firstline.substring(start+"HWaddr ".length(), end).trim();
            }
        }
        return "";
    }
    public static Map<String, String> executeCmdWithOutput(String[] args) {
        Map<String, String> output = new HashMap<String, String>();
        if (args == null || args.length < 1)
            return null;

        boolean isok = false;
        Process process = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder errorMsg = new StringBuilder();
        String firstline = null;
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(args);

            process = processBuilder.start();

            successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
            errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String s;
            while ((s = successResult.readLine()) != null) {
                successMsg.append(s);
                if (firstline == null){
                    firstline = s;
                }
            }

            while ((s = errorResult.readLine()) != null) {
                errorMsg.append(s);
            }

            process.waitFor();

            if (process.exitValue() == 0)
                isok = true;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (process != null) {
                //process.destroy();
                process = null;
            }
        }

        output.put("isok", String.valueOf(isok));
        output.put("successMsg", successMsg.toString());
        output.put("errorMsg", errorMsg.toString());
        output.put("firstline", firstline);
        Timber.d("Execute cmd "+ args[0] + " done, successMsg:" + successMsg + ", ErrorMsg:" + errorMsg);
        return output;
    }

    public static String getMetaData(Context context, String key){
        try {
            ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            String value = appInfo.metaData.getString(key);
            return value;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    private static String mUid;
    public static String getUid(){
        if (TextUtils.isEmpty(mUid)){
            mUid = Utils.getMACAddress("eth0");
            if (mUid.isEmpty()) mUid = Utils.getMACAddress("wlan0");
            mUid = mUid.replaceAll(":", "");
            if (mUid.isEmpty()) mUid="FFFFFFFFFF";
        }
        return mUid;
    }

    public static String getCode(Context context){
        return Utils.getMetaData(context, "code");
    }

    public static boolean isTouchPointInView(View view, int x, int y) {
        if (view == null) {
            return false;
        }
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        int left = location[0];
        int top = location[1];
        int right = left + view.getMeasuredWidth();
        int bottom = top + view.getMeasuredHeight();
        //view.isClickable() &&
        if (y >= top && y <= bottom && x >= left
                && x <= right) {
            return true;
        }
        return false;
    }

    //usa product
    public static boolean isUsaOraoUser(Context context) {
        if ("TPLDHEZP".equals(getCode(context)) || "REQWOXVC".equals(getCode(context)) || "YPPGLSYP".equals(getCode(context)))
            return true;
        return false;
    }
    public static boolean isUsaAisaUser(Context context) {
        if ("HGOTFRKF".equals(getCode(context)))
            return true;
        return false;
    }
}
